package cn._2dland.uploader.utils
{
	import cn._2dland.uploader.task.QQUploadTask;
	import cn._2dland.uploader.task.UploadTaskStatus;
	
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	
	import mx.collections.ArrayCollection;

	public final class TaskHelper {
		public function TaskHelper() {}

		public static function get taskFilePath():String {
			var path:String = File.applicationDirectory.resolvePath("tasks.xml").nativePath;
			return path;
		}

		public static function loadTasks(path:String):ArrayCollection {
			var tasks:ArrayCollection = new ArrayCollection();
			try{
				var tf:File = new File(path);
				if(!tf.exists) throw new Error("file not found!");

				var fs:FileStream = new FileStream();
				fs.open(tf, FileMode.READ);
				var content:String = fs.readUTFBytes(tf.size);
				fs.close();
	
				var taskXML:XML = new XML(content);
				var nodes:XMLList = taskXML.child("task");
				for(var i:int=0; i<nodes.length(); i++){
					var node:XML = XML(nodes[i]);
	
					var t:QQUploadTask = new QQUploadTask(new File(node.file));
					t.title = node.title;
					t.cat = node.cat;
					t.tags = node.tags;
					t.desc = node.desc;
	
					tasks.addItem(t);
				}
			}
			catch(err:Error){
				tasks.removeAll();
			}
			return tasks;
		}

		public static function saveTasks(path:String, tasks:ArrayCollection):void {
			if(tasks==null || tasks.length==0)
				return;
			var tasksXML:XML = new XML("<tasks></tasks>");
			for(var i:int=0; i<tasks.length; i++){
				var t:QQUploadTask = tasks[i] as QQUploadTask;
				if(t.status == UploadTaskStatus.COMPLETE) continue;
				var node:XML = new XML("<task></task>");
				node.title = t.title;
				node.cat = t.cat;
				node.tags = t.tags;
				node.desc = t.desc;
				node.file = t.path;
				tasksXML.appendChild(node);
			}

			var tf:File = new File(path);
			var fs:FileStream = new FileStream();
			fs.open(tf, FileMode.WRITE);
			fs.writeUTFBytes(tasksXML.toXMLString());
			fs.close();
		}
	}
}